using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace OpenWaves.HtmlEncoding
{
    public interface ITokenizer
    {
        IEnumerable<HtmlToken> Tokenize(string text);
    }

    public class LineBreakTokenizer : ITokenizer
    {
        public IEnumerable<HtmlToken> Tokenize(string text)
        {
            var tokens = new List<HtmlToken>();
            for (int i = 0; i < text.Length; i++)
            {
                var isNewLine = text[i] == '\n';
                var isNewLineWithCaretReturn = text[i] == '\r' && ((i + 1 < text.Length) && text[i + 1] == '\n');

                if (isNewLine)
                {
                    tokens.Add(new NewLineToken(i, i));
                }
                else if (isNewLineWithCaretReturn)
                {
                    tokens.Add(new NewLineToken(i, i + 1));

                    //skip '\n' char
                    i++;
                }
            }

            return tokens;
        }
    }

    public class UrlTokenizer : ITokenizer
    {
        public IEnumerable<HtmlToken> Tokenize(string text)
        {
            var tokens = new List<HtmlToken>();
            foreach (Match match in Regex.Matches(text, @"(((http|ftp|https)://([\w@][\w.:@]+)?)|www\.)([^\s<])+([^\.\s<])", RegexOptions.IgnoreCase))
            {
                Url url;
                if (match.Value.StartsWith("www", StringComparison.OrdinalIgnoreCase))
                    url = Url.ParseAbsolute(match.Value);
                else
                    url = Url.Parse(match.Value);

                tokens.Add(new UrlToken(match.Index, match.Index + match.Length - 1, url));
            }
            return tokens;
        }
    }
}